package com.kangfu.api.service.impl;

import cn.hutool.core.util.StrUtil;
import com.kangfu.db.model.bo.wechat.TokenBo;
import com.kangfu.api.service.ITokenService;
import com.kangfu.common.exception.AuthorizationException;
import com.kangfu.common.exception.BusinessException;
import com.kangfu.common.utils.TokenUtils;
import com.kangfu.wechat.utils.JsonUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class TokenServiceImpl implements ITokenService {
    private static final Logger log = LoggerFactory.getLogger(TokenServiceImpl.class);

    /**
     * 解析token
     * @param token
     * @return
     */
    @Override
    public TokenBo verifyToken(String token){
        try {
            Claims claims = TokenUtils.parseJWT(token);
            //获取token内容
            String subject = claims.getSubject();
            //解析token
            TokenBo tokenBo = JsonUtil.parseObject(subject, TokenBo.class);
            if (token == null) {
                throw new AuthorizationException("token解析失败");
            }
            return tokenBo;
        } catch (ExpiredJwtException e) {
            throw new AuthorizationException("token过期");
        } catch (Exception e) {
            throw new AuthorizationException("token解析失败");
        }
    }


    /**
     * 颁发token
     * @param userId
     * @param openid
     * @return
     */
    public String genrateToken(int userId, String openid) {
        TokenBo tokenBo = new TokenBo();
        tokenBo.setUserId(userId);
        tokenBo.setOpenid(openid);
        tokenBo.setAdmin("0");
        String tokenJson = JsonUtil.toJSONString(tokenBo);
        if (StrUtil.isBlank(tokenJson)) {
            throw new BusinessException("颁发token失败");
        }
        return TokenUtils.createJWT(tokenJson);
    }
}
